package com.nitty.cash.loop.ui.activity

import android.graphics.Color
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonActivity
import com.nitty.cash.loop.databinding.UiUserProfileBinding
import com.nitty.cash.loop.event.NittyEventData
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.ui.contract.IViewContract
import com.nitty.cash.loop.ui.presenter.PictureUploadPresenter
import com.nitty.cash.loop.utils.NittyImageUtil
import com.nitty.cash.loop.utils.helper.NittyCustomDataHelper
import com.nitty.cash.loop.utils.imgcovert.ImageConvert
import com.nitty.cash.loop.utils.log.NittyLogger

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/11/28 18:11
 * @Annotation：个人信息
 */
class UserProfileAct: CommonActivity(), IViewContract.IPictureUploadView {
    lateinit var binding: UiUserProfileBinding
    private var presenter: PictureUploadPresenter? = null

    //图片选择
    lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    override fun getNittyRootView(): View {
        binding = UiUserProfileBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#F9F9F9"))
        setNittyTitleBarColor(Color.parseColor("#FFFFFF"))
        setNittyTextTitle(getString(R.string.user_info_title))
        setNittyRightBtnRes(R.mipmap.img_customer_black)
    }

    override fun initNittyListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("User Profile Page")
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_CUSTOMER,"User Profile Page")
            if (binding.editUserName.isFocused){
                binding.editUserName.clearFocus()
            }
        }
        binding.parentLayout.setOnClickListener {
            if (binding.editUserName.isFocused){
                binding.editUserName.clearFocus()
            }
        }
        binding.imgUserPicture.setOnClickListener {
            if (binding.editUserName.isFocused){
                binding.editUserName.clearFocus()
            }
            openUserInfoAlbum()
        }
        //昵称
        binding.editUserName.setOnFocusChangeListener { v, hasFocus ->
            when(hasFocus){
                true -> {//获得焦点
                }
                else -> {//失去焦点
                    val userName = binding.editUserName.text.toString().trim()
                    if (userName.isNotEmpty()){
                        NittyCustomDataHelper.saveNittyCustomUserNameAction(userName)
                    }
                }
            }
        }

        binding.editUserName.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editUserName.clearFocus()
                true
            }
            false
        }

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        NittyLogger.e(">>>>>>>album>>>>>>>>>>$localPath")
                        showNittyLoading(isTOuchOut = false, isCancel = false)
                        presenter!!.submitUploadImageAction(localPath)
                    }
                }
            } else {
                NittyLogger.e("No media selected")
            }
        }
    }

    override fun loadNittyData() {
        setUserInfoData()
    }

    /**
     * 设置用户信息
     */
    private fun setUserInfoData(){
        val avatarUrl = NittyCustomDataHelper.getNittyCustomUserAvatarUrl()
        if (avatarUrl.isNotEmpty()){
            NittyImageUtil.instance.loadImageUrl(this,binding.imgUserPicture,avatarUrl)
        } else {
            binding.imgUserPicture.setImageResource(R.mipmap.img_holder)
        }
        binding.editUserName.setText(NittyCustomDataHelper.getNittyCustomUserName())
    }

    /**
     * 打开相册
     */
    private fun openUserInfoAlbum(){
        if (presenter == null){
            presenter = PictureUploadPresenter(this)
        }
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 图片上传成功
     */
    override fun showUploadPictureSuccess(imgPath: String, imgUrl: String) {
        NittyCustomDataHelper.saveNittyCustomUserAvatar(imgUrl)
    }

    override fun onNittyPublishEvent(event: NittyEventData) {
        super.onNittyPublishEvent(event)
        when(event.eventType){
            NittyEventData.TYPE.NITTY_CUSTOM_DATA_REFRESHED -> {//自定义数据刷新完成
                //设置用户昵称和头像
                setUserInfoData()
            }
            else -> {

            }
        }
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_USER_INFORMATION_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_USER_INFORMATION_END)
    }
}